//
//  IsoWorld.cpp
//  IsoCplus
//
//  Created by 周张林 on 15/9/17.
//
//

#include "IsoWorld.h"
#include "IsoUtil.h"

USING_NS_CC;

IsoWorld* IsoWorld::create(unsigned int size,unsigned int gridX,unsigned int gridZ)
{
    IsoWorld *world = new IsoWorld();
    if(world && world->IsoObject::init(size, gridX, gridZ)){
        world->autorelease();
        return world;
    }
    CC_SAFE_DELETE(world);
    return nullptr;
}


bool IsoWorld::init(unsigned int size,unsigned int gridX,unsigned int gridZ)
{
    if(!IsoObject::init(size, gridX, gridZ))
    {
        return false;
    }
    _scenelayer = Node::create();
    addChild(_scenelayer,1);
    return true;
}

const Vector<IsoScene*> &IsoWorld::getScenes() const
{
    return _scenes;
}

void IsoWorld::addScene(IsoScene *isoScene){
    _scenelayer->addChild(isoScene);
    _scenes.pushBack(isoScene);
}

void IsoWorld::panSceneLayerTo(float x , float y)
{
    _scenelayer->setPosition(Vec2(x, y));
}

float IsoWorld::getSceneOffsetX() const{
    return _scenelayer->getPositionX();
}
float IsoWorld::getSceneOffsetY() const{
    return _scenelayer->getPositionY();
}

Vec2 IsoWorld::pixelPointToGrid(float px, float py, float offsetX, float offsetY){
    auto xx = (px-getPositionX())/getScaleX() - getSceneOffsetX() - offsetX;
    auto yy = (py-getPositionY())/getScaleY() - getSceneOffsetY() - offsetY;
    return IsoUtil::screenToIsoGrid(_size, xx, yy);
}

Vec2 IsoWorld::globalPointToWorld(float px,float py)
{
    auto xx = (px-getPositionX())/getScaleX() - getSceneOffsetX();
    auto yy = (py-getPositionY())/getScaleY() - getSceneOffsetY();
    return Vec2(xx,yy);
}

void IsoWorld::setBg(Node *bg){
    if(this->_bg!=nullptr){
        removeChild(_bg);
        _bg = nullptr;
    }
    _bg = bg;
    addChild(bg,0);
}

void IsoWorld::clearWorld()
{
    for(auto &scene :_scenes)
    {
        scene->clearScene();
    }
    _scenes.clear();
    removeAllChildren();
}

IsoWorld::~IsoWorld(){
    clearWorld();
    _bg = nullptr;
    _scenelayer = nullptr;
}